import 'package:shared_preferences/shared_preferences.dart';

class SpUtils {
  static SpUtils? _instance;
  static SharedPreferences? prefs;

  static Future<SpUtils?> init() async {
    if (_instance == null) {
        // 保持本地实例直到完全初始化。
        var singleton = SpUtils();
        await singleton._init();
        _instance = singleton;
    }
    return _instance;
  }

  Future _init() async {
    prefs = await SharedPreferences.getInstance();
  }

  static putStorage(String key, value) async {
    prefs ??= await SharedPreferences.getInstance();
    if (value is String) {
      prefs?.setString(key, value);
    } else if (value is num) {
      prefs?.setInt(key, value as int);
    } else if (value is double) {
      prefs?.setDouble(key, value);
    } else if (value is bool) {
      prefs?.setBool(key, value);
    } else if (value is List) {
      prefs?.setStringList(key, value.cast<String>());
    }
  }

  // 获取
  static getStorage(String key, [dynamic replace]) async {
    prefs ??= await SharedPreferences.getInstance();
    return prefs?.get(key) ?? replace;
  }

  /// 存储 String 类型数据
  static Future<void> putString(String key, String value) async {
    await prefs?.setString(key, value);
  }

  /// 获取 String 类型数据
  static String getString(String key, [String replace = '']) {
    return prefs?.getString(key) ?? replace;
  }

  /// 存储 int 类型数据
  static Future<void> putInt(String key, int value) async {
    await prefs?.setInt(key, value);
  }

  /// 获取 int 类型数据
  static int getInt(String key, [int replace = 0]) {
    return prefs?.getInt(key) ?? replace;
  }

  /// 存储 bool 类型数据
  static Future<void> putBool(String key, bool value) async {
    await prefs?.setBool(key, value);
  }

  /// 获取 bool 类型数据
  static bool getBool(String key, [bool replace = false]) {
    return prefs?.getBool(key) ?? replace;
  }

  /// 获取 List<String> 类型数据
  static List<String> getStringList(String key, [List<String> replace = const []]) {
    return prefs?.getStringList(key) ?? replace;
  }

  static Future<void> putStringList(String key, List<String> value) async {
    await prefs?.setStringList(key, value);
  }

  /// 清除所有数据
  static Future<void> removeAll() async {
    await prefs?.clear();
  }
}